//
//  BN_DynamicParentData.m
//  BabyNow
//
//  Created by 刘泽琛 on 14-3-29.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "BN_DynamicParentData.h"

@implementation BN_DynamicParentData {
    
    NSArray *files_;
    NSInteger replTime_;
}

// 从网络获得的数据
- (void)loadNetData {
    __weak typeof(self) weakSelf = self;
    _dynamicHelper.queryParentListCompleteHandler = ^(id result,NSString *errorMsg){
        // update by jason yan 2014-05-30
        if (errorMsg) {
            [LZCHINT title:errorMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL];
            weakSelf.listReload(NO ,weakSelf.isScrollToTop);
        }
        if(result){
            [weakSelf useNetDate:result];
        }
    };
    // 测试加载第一页
    [_dynamicHelper refreshParentList];
    
}

// 得到下一页数据
- (void)loadNextNetData {
    __weak typeof(self) weakSelf = self;
    _dynamicHelper.queryParentListCompleteHandler = ^(id result,NSString *errorMsg){
          // update by jason yan 2014-05-30
        if (errorMsg) {
            [LZCHINT title:errorMsg type:LZCError duration:2 places:HINT_PLACES callBack:NULL
             ];
        }
        if (result) {
            [weakSelf useNetDate:result];
        }
    };
    // 测试加载第二页班级动态
    [_dynamicHelper fetchNextPageForParent];
}

// 获得数据 重新加载Tableview
- (void)useNetDate:(id)info {
    self.netArray = (NSMutableArray *)info;
    self.listReload(YES,self.isScrollToTop);
    self.isScrollToTop = NO;
}

- (void)toDynamic_NoticeReloadList:(Dynamic_Notice_ReloadList)reloadList {
    self.listReload = reloadList;
}

- (id)init {
    if (self = [super init]) {
        // 初始化动态Helper
        _dynamicHelper = [[BN_DynamicHelper alloc]init];
        [self performSelectorInBackground:@selector(loadNetData) withObject:nil];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(likeChangeNetArr:) name:K_PARENT_LIKE_NETARRAY_VALUE object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(shareChangeNetArr:) name:K_PARENT_SHARE_NETARRAY_VALUE object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deleChangeNetArr:) name:K_PARENT_DELETE_NETARRAY_VALUE object:nil];
    }
    return self;
}

- (void)tableViewRowForCellReload:(RowForCellReload)rowReload {
    self.rowReload = rowReload;
}

#pragma mark - 刷新控件的代理方法

- (void)upLoadFinished:(MJRefreshBaseView *)refreshView {
    // 列表开始加载，开始数据请求
    // [self loadNetData];
    [self loadNextNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)doneWithView:(MJRefreshBaseView *)refreshView
{
    // 列表开始刷新，开始数据请求
    [self loadNetData];
    
    // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
    [refreshView endRefreshing];
}

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    switch ([refreshView viewType]) {
        case -1:
            [self performSelector:@selector(doneWithView:) withObject:refreshView afterDelay:0.85];
            break;
        case 1:
            [self performSelector:@selector(upLoadFinished:) withObject:refreshView afterDelay:0];
            break;
        default:
            break;
    }
}

- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    // code...
}

- (void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    switch (state) {
        case MJRefreshStateNormal:
            break;
        case MJRefreshStatePulling:
            break;
            
        case MJRefreshStateRefreshing:
            break;
        default:
            break;
    }
}
#pragma mark 列表的委托与dataSource

float currentContentOffset;
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    currentContentOffset = scrollView.contentOffset.y;
    
    // 切换的View隐藏时-慢慢向下拉-拉到最底部时-切换的View显示
    if (currentContentOffset == -99) {
        [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"display"];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    BN_ClassParentCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.cellHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.netArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 配置cell
    static NSString *identifier = @"BN_ClassParentCell";
     BOOL nibsResistered = NO;
     if (!nibsResistered) {
     UINib *nib = [UINib nibWithNibName:NSStringFromClass([BN_ClassParentCell class]) bundle:nil];
     [tableView registerNib:nib forCellReuseIdentifier:identifier];
     nibsResistered = YES;
     }
     BN_ClassParentCell *cell = (BN_ClassParentCell *)[tableView dequeueReusableCellWithIdentifier:identifier];
    cell.tag = indexPath.row;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    for (UIView *view in cell.disPlayImageView.subviews) {
        [view removeFromSuperview];
    }
    for (UIView *view in cell.replView.subviews) {
        [view removeFromSuperview];
    }
    cell.cellHeight = 0;
    cell.relpHeight = 0;
    cell.singleRelpHeight = 0;
    
    // 用户权限
    // NSInteger postUserType = [self.netArray[indexPath.row][@"postUserType"] integerValue];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.postUserId = [self.netArray[indexPath.row][@"postUserId"] integerValue];
    cell.postUserType = [self.netArray[indexPath.row][@"postUserType"] integerValue];
    
    // 用户名称
    cell.userNameLabel.text = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"postUserName"]];
    
    // 发布时间
    NSString *dateStr = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"postDate"]];
    NSRange rang = NSMakeRange(0, 19);
    NSString *strRang = [dateStr substringWithRange:rang];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dateTime = [formatter dateFromString:strRang];
    cell.createTimeLabel.text = [IMB_TimeFormatModel timeFormat:dateTime];
    
    // 浏览次数 browTime
    NSString *browTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"browTime"]];
    if (![browTime isEqual:[NSNull null]]) {
        cell.browseTimeLabel.text = [NSString stringWithFormat:@"浏览%@次",browTime];
    }else {
        cell.browseTimeLabel.text = @"浏览0次";
    }
    
    // 是否收藏
    cell.favoFlg = [self.netArray[indexPath.row][@"favoFlg"] integerValue];
    // 喜欢标记
    cell.praiFlg = [self.netArray[indexPath.row][@"praiFlg"]intValue];
    // 喜欢数
    cell.praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];
    // postId
    cell.postId = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"postId"]];
    // 评论数
    cell.replTime = [self.netArray[indexPath.row][@"replTime"] integerValue];
   
    // 用户头像
    NSString * postHeadUrlStr = self.netArray[indexPath.row][@"postHeadUrl"];
    if (![postHeadUrlStr isEqual:[NSNull null]]) {
        postHeadUrlStr = [THUMBNAIL_BASEURL stringByAppendingString:postHeadUrlStr];
        NSURL *postHeadUrl = [NSURL URLWithString:postHeadUrlStr];
        [cell.userPhotoImageView setImageWithURL:postHeadUrl];
        cell.userPhotoImageView.layer.masksToBounds = YES;
        cell.userPhotoImageView.layer.cornerRadius = 18;
    }else {
        cell.userPhotoImageView.image = [UIImage imageNamed:@"userPhoto"];
    }
    
    NSString *replTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"replTime"]];
    NSString *praiTime = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"praiTime"]];

    if (![replTime isEqual:[NSNull null]]) {
        for (UILabel *view in cell.pinglunBtn.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                [view removeFromSuperview];
            }
        }
        UILabel *pinlunLabel = [[UILabel alloc]init];
        switch (MAIN_VERSION) {
            case 6:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                break;
            default:
                pinlunLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);
                break;
        }
        pinlunLabel.backgroundColor = [UIColor clearColor];
        UIColor *color = APP_OBJECT_GREEN_COLOR;
        pinlunLabel.textColor = color;
        pinlunLabel.font = [UIFont systemFontOfSize:12];
        pinlunLabel.text = replTime;
        [cell.pinglunBtn addSubview:pinlunLabel];
    }
    
    if (![praiTime isEqual:[NSNull null]]) {
        for (UILabel *view in cell.xihuanBtn.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                [view removeFromSuperview];
            }
        }
        UILabel *xihuanLabel = [[UILabel alloc]init];
        switch (MAIN_VERSION) {
            case 6:
                xihuanLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+2, 50, 12);
                break;
            default:
                xihuanLabel.frame = CGRectMake((60-30)/2+17, (31-17)/2+1, 50, 12);
                break;
        }
        xihuanLabel.backgroundColor = [UIColor clearColor];
        UIColor *color = APP_OBJECT_GREEN_COLOR;
        xihuanLabel.textColor = color;
        xihuanLabel.font = [UIFont systemFontOfSize:12];
        xihuanLabel.text = praiTime;
        [cell.xihuanBtn addSubview:xihuanLabel];
    }
    [cell dealLikeBtnColorState];
 
    
    // 评论数组
    cell.replArr = self.netArray[indexPath.row][@"repls"];
    cell.replTime = [self.netArray[indexPath.row][@"replTime"] integerValue];

    // 文字内容
    NSString *postSubj = self.netArray[indexPath.row][@"postSubj"];
    if (![postSubj isEqual:[NSNull null]]) {
        cell.contentTextLabel.text = postSubj;
    }
    
    // UI
    // NSString *fileFlg = [NSString stringWithFormat:@"%@",self.netArray[indexPath.row][@"fileFlg"]];
    NSArray *files = self.netArray[indexPath.row][@"files"];
    [cell groupImageView:files];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
}

// 判断向上或向下滚动
float lastContentOffset;
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    lastContentOffset = scrollView.contentOffset.y;
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    // 解决班级动态UIView和下拉刷新冲突
    if (currentContentOffset > 0) {
        NSLog(@"%f",lastContentOffset);
        if (lastContentOffset < scrollView.contentOffset.y) {
            NSLog(@"向上滚动显示");
            [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"hide"];
            
        }else{
            NSLog(@"向下滚动隐藏");
            [[NSNotificationCenter defaultCenter]postNotificationName:KDISPLAYHIDEDYNAMICUIVIEW object:@"display"];
        }
    }
}

#pragma mark 通知
- (void)likeChangeNetArr:(NSNotification *)notification {
    // praiFlg
    NSArray *recevieArr = notification.object;
    NSInteger tag = [recevieArr[0] integerValue];
    NSInteger praiFlg = [recevieArr[1] integerValue];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    dict = self.netArray[tag];
    // 点赞标记
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)praiFlg] forKey:@"praiFlg"];
    // 点赞次数
    NSInteger praiTime = [dict[@"praiTime"]integerValue];
    switch (praiFlg) {
        case 0:
            praiTime = praiTime - 1;
            break;
        case 1:
            praiTime = praiTime + 1;
            break;
        default:
            break;
    }
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)praiTime] forKey:@"praiTime"];
    [self.netArray replaceObjectAtIndex:tag withObject:dict];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
    NSArray *indexArray = [NSArray arrayWithObject:indexPath];
    self.rowReload(indexArray,NO);
}

- (void)shareChangeNetArr:(NSNotification *)notification {
    NSInteger tag = [notification.object integerValue];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    dict = self.netArray[tag];
    [dict setObject:@"1" forKey:@"favoFlg"];
    [self.netArray replaceObjectAtIndex:tag withObject:dict];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:tag inSection:0];
    NSArray *indexArray = [NSArray arrayWithObject:indexPath];
    self.rowReload(indexArray,NO);
}

- (void)deleChangeNetArr:(NSNotification *)notification {
    NSInteger tag = [notification.object intValue];
    [self.netArray removeObjectAtIndex:tag];
    self.rowReload(nil,YES);
}

#pragma mark dealloc
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KDISPLAYHIDEDYNAMICUIVIEW object:nil];
}

#pragma mark
#pragma mark Notification Action 
- (void)parentRefresh {
    if (!self.dynamicHelper) {
        self.dynamicHelper = [[BN_DynamicHelper alloc]init];
    }
    [self loadNetData];
}

@end
